<template>
	<uni-forms class="login-form" ref="form" :model="formData" :rules="rules">
		<uni-forms-item name="account">
			<input type="text" placeholder="请输入账号" class="uni-input-input" placeholder-style="color: #818181" v-model="formData.account" />
		</uni-forms-item>
		<uni-forms-item name="password">
			<input type="text" placeholder="请输入密码" class="uni-input-input" placeholder-style="color: #818181" v-model="formData.password" />
		</uni-forms-item>
		<button class="submit-button" @click="btn">登录</button>
	</uni-forms>
</template>

<script setup>
import { ref } from 'vue';
import { userAPI } from '@/apis/user.js';
import { tokenArray } from '@/stores/token.js';
import { onLoad } from '@dcloudio/uni-app';

// 回跳地址
const redirectURL = ref('');
// 跳转地址方式
const routeType = ref('');
const tokenA = tokenArray();
const formData = ref({
	account: 'hzhhao',
	password: 'hao123'
});

//验证
const rules = {
	//性能优化
	account: {
		rules: [
			{ required: true, errorMessage: '请输入登录账号' },
			{ pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' }
		]
	},
	password: {
		rules: [
			{ required: true, errorMessage: '请输入登录密码' },
			{ pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录密码格式不正确' }
		]
	}
};

const form = ref();
// 获取地址中的参数
onLoad((query) => {
	redirectURL.value = decodeURIComponent(query.redirectURL);
	routeType.value = query.routeType;
});
//点击登录
const btn = async () => {
	try {
		await form.value.validate();
		// 发送请求
		const res = await userAPI(formData.value);
		console.log('发送表单', res);
		//持久化token
		tokenA.setToken(res.data);
		uni.utils.message('登录成功');
		const url = redirectURL.value === 'undefined' ? '/pages/task/index' : redirectURL.value;
		console.log('url:', url, redirectURL.value);
		uni.utils.push(url);
		// 地址重定向或switchTab
		// if (routeType.value === 'switchTab') {
		// 	uni.switchTab({ url: redirectURL.value });
		// } else {
		// 	uni.redirectTo({
		// 		url: redirectURL.value
		// 	});
		// }
	} catch (error) {
		console.log(error);
	}
};
</script>

<style lang="scss" scoped>
@import './styles.scss';
::v-deep .uni-input-input{
	border:1px solid #ccc !important;
}
</style>
